package it.fuesi.synoutils.services.tasks.filestation;

import android.util.Log;

import it.fuesi.synoutils.adapters.FileStationFilesAdapter;
import it.fuesi.synoutils.helpers.FormatHelper;
import it.fuesi.synoutils.model.filestation.FileStationClientParameters;
import it.fuesi.synoutils.model.filestation.FileStationListDataObject;
import it.fuesi.synoutils.model.filestation.FileStationListResponse;
import it.fuesi.synoutils.services.client.FileStationClient;
import it.fuesi.synoutils.services.client.ServiceClientFactory;
import it.fuesi.synoutils.services.tasks.base.BaseTask;

/**
 * Created by pascotto on 17/10/14.
 */
public class FileStationList extends BaseTask<FileStationListResponse, FileStationListDataObject, FileStationClientParameters> {

    private static final String TAG = FileStationList.class.getName();

    public FileStationList(FileStationFilesAdapter adapter){
        super(adapter);
    }

    public static final String CACHE_KEY_PREFIX = "listFiles_";

    private String currentCacheKey;

    @Override
    protected String getCacheKey() {
        return currentCacheKey;
    }

    @Override
    protected FileStationListResponse doInBackground(FileStationClientParameters... params) {
        FileStationClientParameters param = params[0];
        final String folderPath = param != null ? param.getFolder_path() : null;
        this.currentCacheKey = CACHE_KEY_PREFIX + folderPath;
        return super.doInBackground(params);
    }

    @Override
    public FileStationListResponse run(FileStationClientParameters params)  throws Exception{
            FileStationListResponse resp;

            FileStationClient client = ServiceClientFactory.getClient(FileStationClient.class);

            final String folderPath = params != null ? params.getFolder_path() : null;


            Log.d(TAG, "Fetching data");
            publishProgress("Loading data from disk station");
            if(folderPath != null && !folderPath.isEmpty())
                resp = client.list(FormatHelper.urlEncode(folderPath));
            else {
                resp = client.listShares();
            }


            return resp;


    }


}
